package com.union.estadisticas.pl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class ManagedBean {

	protected String UNIDAD_DE_PERSISTENCIA = "union";
	protected EntityManagerFactory factory;
	protected EntityManager em;

	public ManagedBean() {
		factory = Persistence
				.createEntityManagerFactory(UNIDAD_DE_PERSISTENCIA);
		em = factory.createEntityManager();
	}

	protected void anadir(Object obj) {
		try {
			em.persist(obj);
			em.flush();
			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
		}
	}

	protected void anadirList(List objs) {
		try {
			EntityTransaction entr = em.getTransaction();
			if (!entr.isActive()) {
				entr.begin();
			}
			for (Object obj : objs) {
				em.persist(obj);
				em.flush();
			}
			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
		}
	}

	protected List consultar(String namedQuery) {
		List lista = null;
		try {
			EntityTransaction entr = em.getTransaction();
			if (!entr.isActive()) {
				entr.begin();
			}
			Query query = em.createNamedQuery(namedQuery);
			lista = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lista;
	}

}
